package net.oschina.esb.webmvc.exception.handler;

import net.oschina.esb.exception.CodeException;
import net.oschina.esb.webmvc.view.JsonView;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Arvin
 * @time 2017/12/12 20:40
 */
public class JsonViewExceptionViewResolver implements ExceptionViewResolver {

    @Override
    public boolean canHandle(HandlerMethod handlerMethod) {
        Class<?> returnType = handlerMethod.getMethod().getReturnType();
        return JsonView.class == returnType || JsonView.class == returnType;
    }

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler, Exception ex) {

        if (ex != null) {
            if (ex instanceof CodeException) {
                CodeException exception = (CodeException) ex;
                int code = exception.getCode();
                String errorMessage = exception.getMessage();
                return new JsonView(code, errorMessage);
            }
            return new JsonView(500, ex.getMessage());
        }

        return null;
    }

    @Override
    public int getOrder() {
        return Integer.MAX_VALUE - 1;
    }
}
